﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;

namespace SEOBlog.Web.Helpers
{
    public interface INode
    {
        string Id { get; set; }

        string ParentId { get; set; }
    }

    public class TreeNode<T> where T : INode
    {
        public T Data { get; set; }
        
        public ICollection<TreeNode<T>> ChildNodes { get; set; }

        public TreeNode<T> Parent { get; set; } 
    }

    public class NaryTree<T> where T : INode
    {
        private readonly ICollection<TreeNode<T>> _root;
        
        public NaryTree(ICollection<TreeNode<T>> tree)
        {
            _root = tree;
        }

        private void Add(IEnumerable<TreeNode<T>> root, TreeNode<T> newNode)
        {
            foreach (var treeNode in root)
            {
                if(treeNode.Data.Id == newNode.Data.ParentId)
                {
                    if(treeNode.ChildNodes == null)
                    {
                        treeNode.ChildNodes = new List<TreeNode<T>>();
                    }

                    treeNode.ChildNodes.Add(newNode);
                    newNode.Parent = treeNode;
                }
                else
                {
                    if (treeNode.ChildNodes != null)
                    {
                        Add(treeNode.ChildNodes, newNode);
                    }
                }
            }
        }

        public void Add(T data)
        {
            var newNode = new TreeNode<T> {Data = data};
            Add(_root, newNode);
        }

        private void InOrderTraverse(IEnumerable<TreeNode<T>> root, Action<TreeNode<T>> visitNode, Action<TreeNode<T>> visitLeaf,  ref string res)
        {
            foreach (var treeNode in root)
            {
                if(treeNode.ChildNodes != null)
                {
                    if(treeNode.Parent == null)
                    {
                        res += string.Format("<ul>{0}", treeNode.Data);
                        InOrderTraverse(treeNode.ChildNodes, visitNode, visitLeaf, ref res);
                        res += "</ul>";
                    }
                    else
                    {
                        res += string.Format("<li>{0}<ul>", treeNode.Data);
                        InOrderTraverse(treeNode.ChildNodes, visitNode, visitLeaf, ref res);
                        res += "</ul></li>";
                    }
                }
                else
                {
                    res += string.Format("<li>{0}<li/>", treeNode.Data);
                }
            }
        }

        public string TraverseTree(Action<TreeNode<T>> visitNode, Action<TreeNode<T>> visitLeaf)
        {
            string result = string.Empty;
            InOrderTraverse(_root, visitNode, visitLeaf, ref result);

            return result;
        }
    }
}